import React, { useState, useEffect } from "react";
import getConfig from "next/config";
import Box from "./Box";
import Text from "./Text";
import { Star } from "@styled-icons/boxicons-solid/Star";
import { InfoCircle } from "@styled-icons/boxicons-regular/InfoCircle";
import { BarChart } from "@styled-icons/boxicons-regular/BarChart";
import { Cloud } from "@styled-icons/boxicons-regular/Cloud";
import { Group } from "@styled-icons/boxicons-regular/Group";
import { ChevronDown } from "@styled-icons/boxicons-solid/ChevronDown";
import { ChevronUp } from "@styled-icons/boxicons-solid/ChevronUp";

/**
 * 种子评分详情组件
 */
const TorrentScoreDetails = ({ torrentId, token }) => {
  const [scoreData, setScoreData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [expanded, setExpanded] = useState(false);

  const {
    publicRuntimeConfig: { SQ_API_URL },
  } = getConfig();

  useEffect(() => {
    const fetchScoreDetails = async () => {
      if (!torrentId || !token) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);
        
        const response = await fetch(`${SQ_API_URL}/torrent/score/${torrentId}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        console.log(response);
        
        if (!response.ok) {
          throw new Error(`获取评分
            详情失败: ${response.status}`);
        }

        const data = await response.json();
        setScoreData(data);
      } catch (error) {
        console.error("获取评分详情失败:", error);
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };

    fetchScoreDetails();
  }, [torrentId, token]);

  if (loading) {
    return (
      <Box p={3} bg="sidebar" borderRadius={1}>
        <Text>加载评分详情...</Text>
      </Box>
    );
  }

  if (error) {
    return (
      <Box p={3} bg="sidebar" borderRadius={1}>
        <Text color="error">无法获取评分详情: {error}</Text>
      </Box>
    );
  }

  if (!scoreData || !scoreData.scoreData) {
    return (
      <Box p={3} bg="sidebar" borderRadius={1}>
        <Text>该种子暂无评分数据</Text>
      </Box>
    );
  }

  // 评分数据
  const { scoreData: score } = scoreData;
  const components = score.components || {};
  const technical = components.technical || {};
  const community = components.community || {};

  // 评分可靠性颜色
  const getReliabilityColor = (reliability) => {
    if (reliability < 0.3) return "error";
    if (reliability < 0.7) return "warning";
    return "success";
  };

  // 分数颜色
  const getScoreColor = (score) => {
    if (score < 40) return "error";
    if (score < 70) return "warning";
    return "success";
  };

  // 评分可靠性文本
  const getReliabilityText = (reliability) => {
    if (reliability < 0.3) return "低";
    if (reliability < 0.7) return "中";
    return "高";
  };

  return (
    <Box p={3} bg="sidebar" borderRadius={1} mb={4}>
      <Box
        display="flex"
        justifyContent="space-between"
        alignItems="center"
        cursor="pointer"
        onClick={() => setExpanded(!expanded)}
      >
        <Box display="flex" alignItems="center">
          <Star size={24} color="#FFD700" />
          <Text ml={2} fontWeight="bold" fontSize={2}>
            评分详情
          </Text>
        </Box>
        <Box display="flex" alignItems="center">
          <Text
            mr={2}
            fontSize={3}
            fontWeight="bold"
            color={getScoreColor(score.finalScore)}
          >
            {score.finalScore}/10
          </Text>
          {expanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
        </Box>
      </Box>

      {expanded && (
        <Box mt={3}>
          <Box mb={3}>
            <Text mb={2} fontWeight="bold">
              <InfoCircle size={16} style={{ verticalAlign: "text-bottom" }} />{" "}
              评分可靠性:
              <Text
                as="span"
                ml={1}
                color={getReliabilityColor(score.reliability)}
              >
                {getReliabilityText(score.reliability)}
              </Text>
              <Text as="span" fontSize={1} color="grey" ml={1}>
                ({Math.round(score.reliability * 100)}%)
              </Text>
            </Text>
            <Text fontSize={1} color="grey">
              评分可靠性基于评价数量和种子活跃度，评价越多可靠性越高
            </Text>
          </Box>

          <Box mb={3}>
            <Text fontSize={2} fontWeight="bold" mb={2}>
              <BarChart size={16} style={{ verticalAlign: "text-bottom" }} />{" "}
              评分维度 评分维度
            </Text>

            <Box display="flex" flexDirection="column">
              <ScoreItem
                label="技术维度"
                score={score.technicalScore}
                description="资源下载成功率和健康度"
                weight={30}
              />

              <ScoreItem
                label="内容维度"
                score={score.contentScore}
                description="用户对资源质量的评价"
                weight={50}
              />

              <ScoreItem
                label="社区维度"
                score={score.communityScore}
                description="问题响应和长期价值"
                weight={20}
              />
            </Box>
          </Box>

          <Text fontSize={2} fontWeight="bold" mb={2}>
            <Cloud size={16} style={{ verticalAlign: "text-bottom" }} />{" "}
            技术详情 技术详情
          </Text>

          <Box display="flex" justifyContent="space-between" mb={2}>
            <Text fontSize={1}>下载成功率:</Text>
            <Text fontSize={1}>
              {technical.successRate !== undefined
                ? Math.round(technical.successRate * 100)
                : 0}
              %
            </Text>
          </Box>

          <Box display="flex" justifyContent="space-between" mb={3}>
            <Text fontSize={1}>做种节点数:</Text>
            <Text fontSize={1}>{technical.seeders ?? 0}</Text>
          </Box>

          <Box>
            <Text fontSize={2} fontWeight="bold" mb={2}>
              <Group size={16} style={{ verticalAlign: "text-bottom" }} />{" "}
              社区参与 社区参与
            </Text>

            <Box display="flex" justifyContent="space-between" mb={2}>
              <Text fontSize={1}>问题响应时间:</Text>
              <Text fontSize={1}>
                {community.responseTime !== undefined
                  ? community.responseTime < 12
                    ? "< 12小时"
                    : community.responseTime < 48
                    ? "12-48小时"
                    : "> 48小时"
                  : "-"}
              </Text>
            </Box>

            <Box display="flex" justifyContent="space-between" mb={2}>
              <Text fontSize={1}>讨论数量:</Text>
              <Text fontSize={1}>{community.discussions ?? 0}</Text>
            </Box>

            <Box display="flex" justifyContent="space-between">
              <Text fontSize={1}>资源年龄:</Text>
              <Text fontSize={1}>{community.age ?? 0}天</Text>
            </Box>
          </Box>
        </Box>
      )}
    </Box>
  );
};

/**
 * 评分项目组件
 */
const ScoreItem = ({ label, score, description, weight }) => {
  // 分数颜色
  const getScoreColor = (score) => {
    if (score < 40) return "error";
    if (score < 70) return "warning";
    return "success";
  };

  return (
    <Box mb={2}>
      <Box display="flex" justifyContent="space-between" mb={1}>
        <Text fontSize={1}>
          {label}
          <Text as="span" fontSize={1} color="grey" ml={1}>
            ({weight}%)
          </Text>
        </Text>
        <Text fontSize={1} fontWeight="bold" color={getScoreColor(score)}>
          {score.toFixed(1)}
        </Text>
      </Box>

      <Box display="flex" alignItems="center">
        <Box
          height="6px"
          width="100%"
          bg="background"
          borderRadius={4}
          overflow="hidden"
        >
          <Box height="100%" width={`${score}%`} bg={getScoreColor(score)} />
        </Box>
      </Box>

      <Text fontSize={0} color="grey" mt={1}>
        {description}
      </Text>
    </Box>
  );
};

export default TorrentScoreDetails;
